﻿using Infrastructure.WebApi;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Infrastructure.Extension
{
    public static class IQueryableExtension
    {
        #region 对IQueryable进行分页
        /// <summary>
        /// 得到IQueryable的分页后实体集合
        /// </summary>
        /// <param name="query"></param>
        /// <param name="pageSize">每页多少条数据</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="isTotal">是否统计总行数</param>
        /// <returns></returns>
        public static async Task<Page<T>> PageAsync<T>(this IQueryable<T> query, int pageIndex, int pageSize, bool isTotal = true)
        {
            Page<T> list = new Page<T>();
            if (isTotal)
            {
                list.TotalCount = await query.CountAsync();
            }
            list.List = await query._queryPage(pageIndex, pageSize).ToListAsync();
            return list;
        }
        public static Page<T> Page<T>(this IQueryable<T> query, int pageIndex, int pageSize, bool isTotal = true)
        {
            Page<T> list = new Page<T>();
            if (isTotal)
            {
                list.TotalCount = query.Count();
            }
            list.List = query._queryPage(pageIndex, pageSize).ToList();
            return list;
        }

        /// <summary>
        /// 对IQueryable进行分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="pageSize">每页多少条数据</param>
        /// <param name="pageIndex">当前页</param>
        /// <returns></returns>
        private static IQueryable<T> _queryPage<T>(this IQueryable<T> query, int pageIndex, int pageSize)
        {
            if (pageIndex <= 0) pageIndex = 1;
            if (pageSize <= 0) pageSize = 1;
            if (pageSize > 0)
                return query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            return query;
        }
        #endregion

        //#region IEnumerable<T>.WhereIF()方法
        //public static IQueryable<T> WhereIf<T>(this IQueryable<T> queryable, bool condition, Expression<Func<T, bool>> predicate)
        //{
        //    if (condition) queryable = queryable.Where(predicate);

        //    return queryable;
        //}
        //#endregion
    }
}
